package com.htht.smartschool.common.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.htht.smartschool.model.course.TCourse;
import com.htht.smartschool.model.exam.TExaminationresult;
import com.htht.smartschool.model.student.TStudent;
import com.htht.smartschool.model.teacher.TTeacher;
import com.htht.smartschool.service.course.CourseService;
import com.htht.smartschool.service.student.StudentService;
import com.htht.smartschool.service.teacher.TeacherService;
import com.htht.smartschool.util.system.ExcelUtil;
import com.htht.smartschool.util.system.MapUtil;

/**
 * 
 * @author XHW
 * 
 * @date 2011-7-26
 * 
 */
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = -7744625344830285257L;

	TeacherService ts = new TeacherService();
	StudentService ss = new StudentService();
	CourseService  cu = new CourseService();
	private ServletContext sc;
	// 保存文件的目录
	private static String PATH_FOLDER = "/";
	// 存放临时文件的目录
	private static String TEMP_FOLDER = "/";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void init(ServletConfig config) {
		sc = config.getServletContext();
		// 保存文件的目录
		PATH_FOLDER = sc.getRealPath("/uploads/excle");
		// 存放临时文件的目录,存放xxx.tmp文件的目录
		TEMP_FOLDER = sc.getRealPath("/uploads/temp");
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		String clazz = request.getParameter("clazz");
		String schoolid = request.getParameter("schoolid");
		String classcode = request.getParameter("classcode");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(TEMP_FOLDER));
		factory.setSizeThreshold(1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		Result result = new Result();
		PrintWriter out = response.getWriter();
		try {
			List<FileItem> list = upload.parseRequest(request);
			// 获取上传的文件
			FileItem item = getUploadFileItem(list);
			// 获取文件名
			String filename = getUploadFileName(item);
			item.write(new File(PATH_FOLDER, filename));
			Map map = new HashMap();
			Map saveData = saveData(PATH_FOLDER + "/" + filename, clazz,schoolid,classcode);
			boolean filedel = removefile(PATH_FOLDER + "/" + filename);
			map.put("fail", saveData);
			map.put("filedel", filedel);
			result.setOK(map);
		} catch (Exception e) {
			result.setResult(0);
			result.setError(e.getMessage());
		}
		out.print(result.toJSON());
		out.flush();
		out.close();
	}

	public boolean removefile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (file.exists()) {
			flag = file.delete();
		}
		return flag;
	}
//	public static void main(String[] args) {
//		TStudent ts = new TStudent();
//		ts.set名字("小伙");
//		ts.get名字();
//		System.out.println(ts.get名字());
//	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map saveData(String path, String clazz,String schoolcode,String classcode) throws InvocationTargetException, ParseException {
		List list = ExcelUtil.getInstance().readExcel(path);
		Map result = new HashMap();
		if(list.size() == 0){
			result.put("data", "excel格式错误");
		}
		if (clazz.equalsIgnoreCase("student")) {
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				TStudent ts = (TStudent) MapUtil
						.convertMap(TStudent.class, map);
				ts.setSchoolcode(schoolcode);
				ts.setClasscode(classcode);
				//必须同时满足这三个条件
				if(ts.getPhone() != null && ts.getPhone().length() >0 && ts.getImei() != null && ts.getImei().length() >0 &&  ts.getRfid() != null && ts.getRfid().length()>0){
					TStudent tstudent = ss.addStudent(ts);
					if (tstudent.getStudentcode().equalsIgnoreCase("学生编码存在") || tstudent.getStudentcode().equalsIgnoreCase("家长编码存在,是否绑定到此家长")) {
						result.put(ts.getStudentcode(), false);
					}else{
						result.put("data", "1");
					}
				}
			}
		} else if (clazz.equalsIgnoreCase("teacher")) {
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				TTeacher tt = (TTeacher) MapUtil
						.convertMap(TTeacher.class, map);
				boolean tteacher = ts.addTeacher(tt);
				if (!tteacher) {
					result.put(tt.getTeachercode(), false);
				}else{
					result.put("data", "1");
				}
			}
		} else if (clazz.equalsIgnoreCase("examinationresult")) {
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				TExaminationresult te = (TExaminationresult) MapUtil
						.convertMap(TExaminationresult.class, map);
				int j = ts.addExaminationresult(te);
				if (j == -1) {
					result.put(te.getStudentcode(), false);
				}else{
					result.put("data", "1");
				}
			}
		}else if(clazz.equalsIgnoreCase("exportCourse")){
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map) list.get(i);
				TCourse tc = (TCourse) MapUtil.convertMap(TCourse.class, map);
					tc.setClasscode(classcode);
				  boolean TCourse = cu.addCourse(tc);
				  if (!TCourse) {
						result.put(tc.getTeachercode(), false);
					}else{
						result.put("data", "1");
					}
			}
		}
		return result;
	}

	private FileItem getUploadFileItem(List<FileItem> list) {
		for (FileItem fileItem : list) {
			if (!fileItem.isFormField()) {
				return fileItem;
			}
		}
		return null;
	}

	private String getUploadFileName(FileItem item) {
		// 获取路径名
		String value = item.getName();
		String[] values = value.split("\\.");
		String uuid = UUID.randomUUID().toString();
		StringBuffer sbRealPath = new StringBuffer();
		sbRealPath.append(uuid).append(".").append(values[1]);
		return sbRealPath.toString();
	}
}